package com.iwinding.ladygg.ui.act;

import android.Manifest;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.request.AddFriendReq;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.runtimepermissions.PermissionsManager;
import com.iwinding.ladygg.runtimepermissions.PermissionsResultAction;
import com.iwinding.ladygg.utils.LogUtil;
import com.iwinding.ladygg.utils.ToastUtil;

import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.QRCodeDecoder;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

/**
 * Created by hezhiyong on 2017/4/6.
 */

public class ScanActivity extends BaseActivity implements View.OnClickListener, QRCodeView.Delegate {

    private static final String TAG = ScanActivity.class.getSimpleName();
    private static final int REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY = 666;
    private static final int PERMISSIONS_CAMERA = 555;

    private ZXingView zXingView;
    private final static int SCAN_PHOTO = 102;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();

        PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, new PermissionsResultAction() {
            @Override
            public void onGranted() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        vibrate();
                        zXingView.startSpot();
                    }
                });
            }

            @Override
            public void onDenied(String permission) {
                ToastUtil.openBaseToast(mContext, permission, Toast.LENGTH_SHORT);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
//        vibrate();
//        zXingView.startSpot();
    }

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_scan;
    }

    void initView() {
        setBackTxtResId(R.string.icane_add_friends);
        setTitleResId(R.string.icane_scan);
        setRightTxtResId(R.string.icane_album);

        findViewById(R.id.lay_right).setOnClickListener(this);
        zXingView = (ZXingView) findViewById(R.id.zxingview);
        zXingView.setDelegate(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_right:
//                startActivityForResult(new Intent(this, SelectPicActivity.class), SCAN_PHOTO);
                /*
                 从相册选取二维码图片，这里为了方便演示，使用的是
                 https://github.com/bingoogolapple/BGAPhotoPicker-Android
                 这个库来从图库中选择二维码图片，这个库不是必须的，你也可以通过自己的方式从图库中选择图片
                 */
                startActivityForResult(BGAPhotoPickerActivity.newIntent(this, null, 1, null, false), REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY);
                break;
        }
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(1000);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        LogUtil.i("@hzy", "result=" + result);
//        http://120.77.22.230:8080/omh/oAuth/resources/user/searchFriend?userId=3
        ToastUtil.openBaseToast(this, result, Toast.LENGTH_SHORT);
        String def_str = "userId=";
        String userId = result.substring(result.indexOf(def_str) + def_str.length(), result.length());
        if (TextUtils.isEmpty(userId)) {
            vibrate();
            zXingView.startSpot();
        } else {
            startNewUser(userId);
            finish();
        }

    }

    void startNewUser(final String userId) {
//        Intent toadd = new Intent(mContext, SendMsgActivity.class);
//        toadd.putExtra(SendMsgActivity.USERNAME,userId);
//        mContext.startActivity(toadd);
        AddFriendReq req = new AddFriendReq();
        req.userId = userId;
        RequestManager.postAddFriend(mContext, req, new BaseRpCallback<BaseRopnse>() {
            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse o) {
                try {
                    EMClient.getInstance().contactManager().addContact(userId, mContext.getString(R.string.icane_add_user));
                    ToastUtil.openBaseToast(mContext, R.string.icane_add_ok, Toast.LENGTH_SHORT);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }

        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        zXingView.startCamera();
//        mQRCodeView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);

        zXingView.showScanRect();
    }

    @Override
    protected void onStop() {
        zXingView.stopCamera();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        zXingView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        ToastUtil.openBaseToast(this, "打开相机出错", Toast.LENGTH_SHORT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        zXingView.showScanRect();

        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_QRCODE_FROM_GALLERY) {
            final String picturePath = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            LogUtil.i("@hzy", "onActivityResult=" + picturePath);
            /*
            这里为了偷懒，就没有处理匿名 AsyncTask 内部类导致 Activity 泄漏的问题
            请开发在使用时自行处理匿名内部类导致Activity内存泄漏的问题，处理方式可参考 https://github.com/GeniusVJR/LearningNotes/blob/master/Part1/Android/Android%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F%E6%80%BB%E7%BB%93.md
             */
            new MyAsyncTask(picturePath).execute();

        }
    }

    class MyAsyncTask extends AsyncTask<Void, Void, String> {

        private String picturePath;

        public MyAsyncTask(String picturePath) {
            this.picturePath = picturePath;
        }

        @Override
        protected String doInBackground(Void... params) {
            return QRCodeDecoder.syncDecodeQRCode(picturePath);
        }

        @Override
        protected void onPostExecute(String result) {
            if (TextUtils.isEmpty(result)) {
                ToastUtil.openBaseToast(ScanActivity.this, "未发现二维码", Toast.LENGTH_SHORT);
            } else {
                LogUtil.i("@hzy", "result=" + result);
                ToastUtil.openBaseToast(ScanActivity.this, result, Toast.LENGTH_SHORT);
            }
        }

    }

}
